package com.alibaba.incubator.loadtestermini.model.load;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.alibaba.incubator.loadtestermini.model.behavior.organism.Session;
import com.alibaba.incubator.loadtestermini.util.distribution.DistributionUtils;
import com.alibaba.incubator.loadtestermini.util.distribution.IntervalItem;

/**
 * (created at 2010-5-27)
 * 
 * @author <a href="mailto:shuo.qius@alibaba-inc.com">QIU Shuo</a>
 */
public class SessionDistribution {
    private DistributionUtils<Session> distributionUtil = new DistributionUtils<Session>();
    private List<IntervalItem<Session>> sessionDist;

    public SessionDistribution(Map<Session, Double> sessionDistribution) {
        if (sessionDistribution == null)
            throw new IllegalArgumentException("argument 'sessionDistribution' is null!");
        Map<Session, Double> map = new HashMap<Session, Double>();
        for (Session session : sessionDistribution.keySet()) {
            Double value = sessionDistribution.get(session);
            if (value != null && value > 0)
                map.put(session, value);
        }
        if (map.isEmpty())
            throw new IllegalArgumentException("argument 'sessionDistribution' has no valid value!");
        sessionDist = distributionUtil.normalize(map);
    }

    /**
     * thread-safe
     */
    public Session selectSession() {
        return distributionUtil.selectFromDistribution(sessionDist);
    }
}
